package capstoneproject.dudiachi.Main;

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

public class GoogleMapFragment extends Fragment {

	private static GoogleMap map;

	public GoogleMapFragment() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			return null;
		}
		View v = inflater.inflate(R.xml.google_map_fragment, container, false);
		setUpMapIfNeeded();
//		map = ((SupportMapFragment) GoogleMapActivity.fragmentManager
//				.findFragmentById(R.id.map)).getMap();
		return v;
	}

	public static void setUpMapIfNeeded() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (map == null) {
			// Try to obtain the map from the SupportMapFragment.
			map = ((SupportMapFragment) GoogleMapActivity.fragmentManager
					.findFragmentById(R.id.map)).getMap();
			// Check if we were successful in obtaining the map.
			if (map != null)
				setUpMap();
		}

	}

	// private static void setUpMap() {
	// // For showing a move to my loction button
	// map.setMyLocationEnabled(true);
	// // For dropping a marker at a point on the Map
	// map.addMarker(new MarkerOptions().position(new LatLng(latitude,
	// longitude)).title("My Home").snippet("Home Address"));
	// // For zooming automatically to the Dropped PIN Location
	// map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
	// longitude), 12.0f));
	// }

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		try {
			GoogleMapActivity.fragmentManager
					.beginTransaction()
					.remove(GoogleMapActivity.fragmentManager
							.findFragmentById(R.id.map)).commit();
		} catch (Exception e) {
		}
	}

	private static void setUpMap() {
		map.setMyLocationEnabled(true);
		Location myLocation = GoogleMapActivity.myLocation;
		if (myLocation != null) {
			LatLng myLatLng = new LatLng(myLocation.getLatitude(),
					myLocation.getLongitude());
			CameraPosition myPos = new CameraPosition.Builder()
					.target(myLatLng).zoom(16).build();
			map.animateCamera(CameraUpdateFactory.newCameraPosition(myPos));
		} else
			map.clear();
	}

}
